<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\OrderAppraise;
use app\common\model\Recovery;
use app\common\model\UserAddress;
use app\common\model\UserRecyclerInfo;
use think\Config;
use think\Db;
use think\Hook;

class Order extends Api
{

    /**
     * 下单初始化接口
     */
    public function init()
    {
        $weight_types = [
            ['value' => 1, 'text' => '10~50'],
            ['value' => 2, 'text' => '50~100'],
            ['value' => 3, 'text' => '100以上'],
        ];

        $operatingHours = [];
        for ($i = 9; $i < 19; $i ++) {
            $time = $i < 10 ? '0' . $i : $i;
            $operatingHours[] = ['value' => $time . ':00', 'label' => $time . ':00'];
            $operatingHours[] = ['value' => $time . ':30', 'label' => $time . ':30'];
        }
        $operatingHours[]   = ['value' => '19:00', 'label' => '19:00'];
        $defaultHour = date('H:i', strtotime('+ 30 minutes'));
        $defaultHour = $defaultHour < '09:00' ? '09:00' : $defaultHour;
        $defaultHour = $defaultHour > '19:00' ? '19:00' : $defaultHour;

        $this->success('', [
            'weight_types'      => $weight_types,
            'address_id'        => UserAddress::where(['user_id' => $this->auth->id, 'is_default' => 1])->value('id', 0),
            'article_id'        => 2,
            'proportion'        => Config::get('site.integral_proportion'),
            'operating_hours'   => $operatingHours,
            'default_hour'      => $defaultHour,
            'points_ignored'    => [9, 10], // 铜类不计算积分
            'wechat_tmpl_ids'   => ['lJp9bid7nvrUz1dVqKwuPCx8HW1hvGakzJG_4f4Nm9k'],
            'proposed_price'    => (new Recovery())->getAGuidePrice(['region_id' => $this->auth->region_id]),
        ]);
    }

    /**
     * 我的订单
     */
    public function index()
    {
        $params = [
            'where' => [
                'user_id' => $this->auth->id
            ]
        ];

        if ($this->request->has('status')) {
            $params['where']['status'] = $this->request->param('status');
        }

        $order  = new \app\common\model\Order();
        $list   = $order->getList($params);

        $this->success('', ['total' => $list->total(), 'rows' => $list->items()]);
    }

    /**
     * 订单评价
     */
    public function comment()
    {
        $params = [
            'order_id'  => $this->request->post('order_id', 0),
            'user_id'   => $this->auth->id,
            'receiving' => $this->request->post('receiving', 1),
            'come'      => $this->request->post('come', 1),
            'service'   => $this->request->post('service', 1),
            'evaluate'  => $this->request->post('evaluate', '暂无评价'),
        ];
        $appraiseModel = new OrderAppraise();
        if (!$appraiseModel->orderComment($params)) {
            $this->error($appraiseModel->getError());
        }

        $this->success();
    }

    /**
     * 订单详情
     * @param $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($id)
    {
        $orderModel = new \app\common\model\Order();
        $params = [
            'where'         => [
                'id'        => $id,
                'user_id'   => $this->auth->id
            ],
            'is_details'    => true
        ];
        $row = $orderModel->getDetail($params);
        if (!$row) {
            $this->error($orderModel->getError());
        }

        $this->success('', $orderModel->getData());
    }

    /**
     * 订单取消
     * @param $id
     */
    public function cancel($id)
    {
        $orderModel = new \app\common\model\Order();

        $params = [
            'where' => [
                'id'        => $id,
                'user_id'   => $this->auth->id
            ]
        ];
        $row = $orderModel->cancel($params);

        if (!$row) {
            $this->error($orderModel->getError());
        }

        $this->success();
    }

    /**
     * 回收员订单列表
     */
    public function recyclerlist()
    {
        $recyclerModel = new UserRecyclerInfo();
        if (!$recyclerModel->getDetail(['where' => ['user_id' => $this->auth->id]])) {
            $this->error($recyclerModel->getError());
        }

        $recycler   = $recyclerModel->getData();
        $params     = ['where' => [
            'region_id'     => $recycler['region_id'],
            'recycler_id'   => ['IN', [0, $recycler['id']]]
        ]];

        if ($this->request->has('status')) {
            $params['where']['status'] = $this->request->param('status');
        }

        $order  = new \app\common\model\Order();
        $list   = $order->getList($params);

        $this->success('', ['total' => $list->total(), 'rows' => $list->items()]);
    }

    /**
     * 回收员订单详情
     */
    public function recyclerdetail($id)
    {
        $recyclerModel = new UserRecyclerInfo();
        if (!$recyclerModel->getDetail(['where' => ['user_id' => $this->auth->id], 'is_details' => true])) {
            $this->error($recyclerModel->getError());
        }

        $recycler = $recyclerModel->getData();
        $params = [
            'where'             => [
                'id'            => $id,
                'region_id'     => $recycler['region_id'],
                'recycler_id'   => ['IN', [0, $recycler['id']]]
            ],
            'is_details'        => true,
            'is_address_type'   => true,
        ];
        $orderModel = new \app\common\model\Order();
        if (!$orderModel->getDetail($params)) {
            $this->error($orderModel->getError());
        }

        $data = $orderModel->getData();
        $data['region_name'] = Db::name('region')->where('id', $recycler['region_id'])->value('name', '片区名称');
        $this->success('', $data);
    }

    /**
     * 回收员接单
     * @param $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ordertaking($id)
    {
        $orderModel = new \app\common\model\Order();
        $params     = [
            'id'                => $id,
            'recycler_user_id'  => $this->auth->id,
        ];

        if (!$orderModel->orderTaking($params)) {
            $this->error($orderModel->getError());
        }

        $this->success();
    }

    /**
     * 添加
     */
    public function add()
    {
        $params = $this->request->post();

        $data = [
            'user'      => &$this->auth,
            'address'   => $params
        ];
        Hook::listen('user_region_handle', $data);

        $params['region_id']    = $this->auth->region_id;
        $params['user_id']      = $this->auth->id;
        $params['images']       = isset($params['images']) ? (is_array($params['images']) ? implode(',', $params['images']) : $params['images']) : '';

        $orderModel = new \app\common\model\Order();
        if (!$orderModel->addRecycleOrder($params)) {
            $this->error($orderModel->getError());
        }

        $this->success();
    }

    /**
     * Name: 结算
     * Date: 2021/12/18 15:16
     */
    public function settlement()
    {
        $params = [
            'id'            => $this->request->param('id'),
            'region_id'     => $this->auth->region_id,
            'recovery_id'   => explode(',', $this->request->param('recovery_ids', '')),
            'number'        => explode(',', $this->request->param('numbers', '')),
        ];

        $orderModel = new \app\common\model\Order();
        if (!$orderModel->settlement($params)) {
            $this->error($orderModel->getError());
        }
        $this->success();
    }
}